package com.lagou;

import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Iterator;

public class WorkDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        //1、获取流数据源
        DataStreamSource<Tuple2<String, Long>> data = env.addSource(new SourceFunction<Tuple2<String, Long>>() {
            @Override
            public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
                int num = 0;
                long time = 0l;
                while (true) {
                    num++;
                    time = System.currentTimeMillis();
                    ctx.collect(new Tuple2<>("name" + num%5, time));
                    Thread.sleep(100);
                }
            }
            @Override
            public void cancel() {

            }
        });
        SingleOutputStreamOperator<Tuple2<String, Long>> watermarks =  data.assignTimestampsAndWatermarks(new WatermarkStrategy<Tuple2<String, Long>>() {

            @Override
            public WatermarkGenerator<Tuple2<String, Long>> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {

                return new WatermarkGenerator<Tuple2<String, Long>>() {

                    long maxTimeStamp = Long.MIN_VALUE;
                    long maxOutOfOrderness = 500l;

                    @Override
                    public void onEvent(Tuple2<String, Long> event, long l, WatermarkOutput watermarkOutput) {
                        maxTimeStamp = Math.max(maxTimeStamp, event.f1);
                    }

                    @Override
                    public void onPeriodicEmit(WatermarkOutput output) {
                        output.emitWatermark(new Watermark(maxTimeStamp - maxOutOfOrderness));
                    }
                };
            }
        }.withTimestampAssigner((element, recordTimestamp) -> element.f1));

        KeyedStream<Tuple2<String, Long>, String> keyed = watermarks.keyBy(value -> value.f0);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        //state代码
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMaped = keyed.flatMap(new RichFlatMapFunction<Tuple2<String, Long>, Tuple2<String, Long>>() {
            ValueState<Tuple2<String, Long>> sumState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //在open方法中做出State
                ValueStateDescriptor<Tuple2<String, Long>> descriptor = new ValueStateDescriptor<>(
                        "time",
                        TypeInformation.of(new TypeHint<Tuple2<String, Long>>() {}),
                        Tuple2.of("", 0L)
                );

                sumState = getRuntimeContext().getState(descriptor);
                super.open(parameters);
            }

            @Override
            public void flatMap(Tuple2<String, Long> value, Collector<Tuple2<String, Long>> out) throws Exception {
                //在flatMap方法中，更新State
                Tuple2<String, Long> currentSum = sumState.value();

                currentSum.f1 = Math.max(value.f1, currentSum.f1);
                currentSum.f0 = value.f0 + " latestTime: " + sdf.format(currentSum.f1);


                sumState.update(currentSum);
                out.collect(new Tuple2<>(currentSum.f0, currentSum.f1));

            }
        });
        flatMaped.print();

        //获取窗口
        WindowedStream<Tuple2<String, Long>, String, TimeWindow> timeWindow = keyed.timeWindow(Time.seconds(5));

        //操作窗口数据
        SingleOutputStreamOperator<String> applyed = timeWindow.apply(new WindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow window, Iterable<Tuple2<String, Long>> input, Collector<String> out) throws Exception {
                Iterator<Tuple2<String, Long>> iterator = input.iterator();
                StringBuilder sb = new StringBuilder();
                System.out.println("...............");
                while (iterator.hasNext()) {
                    Tuple2<String, Long> next = iterator.next();
                    sb.append(next.f1 + "..." );

                }
                String s1 = s + "..." + sdf.format(window.getStart()) + "..." + sdf.format(window.getEnd())+ "..." + sb;
                out.collect(s1);

            }
        });

        //输出窗口数据
        applyed.print();
        env.execute();
    }

}
